package com.yuanhang.readsms.receiver;

import static com.yuanhang.readsms.MainActivity.handler;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.telephony.SmsMessage;

import com.yuanhang.readsms.bean.Phone;

import org.litepal.LitePal;

import java.util.List;

/**
 * created by cwj on 2024-8-20
 * Description:短信接收器广播
 */
public class SmsBroadcastReceiver extends BroadcastReceiver {

    public SmsBroadcastReceiver() {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                for (Object pdu : pdus) {
                    SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
                    String sender = sms.getOriginatingAddress();
//                    String messageBody = sms.getMessageBody();

                    List<Phone> allPhone = LitePal.findAll(Phone.class);
                    // 检查发送者是否是你想要拦截的特定号码
                    for (int i = 0; i < allPhone.size(); i++) {
                        if (allPhone.get(i).getPhoneNum().equals(sender)) {
                            // 保存短信到数据库或文件
                            Message message = handler.obtainMessage(200, sms);
                            message.arg1 = 0;
                            handler.sendMessage(message);
                        }
                    }
                }
            }
        }
    }
}
